package com.todo.content.application.mq.receiver;

import com.alibaba.fastjson.JSONObject;
import com.todo.component.redis.RedisService;
import com.todo.content.application.base.conf.ContentRabbitConfig;
import com.todo.content.application.entity.context.ContentStatusContext;
import com.todo.content.application.handler.changeStatus.AbstractContentStatusHandler;
import com.todo.content.application.handler.changeStatus.ContentStatusFactory;
import com.todo.content.application.mq.entity.ContentStatusChangeEntity;
import com.todo.content.common.base.ContentKeyBuild;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author azhebuxing
 * @date 2024/12/11 02:40
 * @description
 */
@Slf4j
@Component
public class ContentStatusChangeReceiver {

    @Resource
    private RedisService redisService;
    @Resource
    private ContentStatusFactory contentStatusFactory;

    @RabbitListener(queues = ContentRabbitConfig.CONTENT_STATUS_CHANGE_QUEUE)
    public void receiveMessage(Message message) {

        String messageId = message.getMessageProperties().getMessageId();
        String idempotentKey = ContentKeyBuild.contentStatusChangeIdempotentKey(messageId);
        if (redisService.hasKey(idempotentKey)) {
            //当前似乎逻辑为默认执行成功，后续调整ACK即可
            log.info("ContentStatusChangeReceiver 当前状态数据已经处理或处理中，默认消息重试 messageId：{}", messageId);
            return;
        }
        //默认缓存10min
        redisService.set(idempotentKey, "ok", 10 * 60);

        String messageBody = new String(message.getBody());
        ContentStatusChangeEntity entity = JSONObject.parseObject(messageBody, ContentStatusChangeEntity.class);
        if (entity == null) {
            return;
        }
        AbstractContentStatusHandler handle = contentStatusFactory.getHandle(entity.getCurrentStatus());
        if (handle == null) {
            return;
        }
        ContentStatusContext context = new ContentStatusContext();
        context.setContentId(entity.getContentId());
        context.setCurrentStatus(entity.getCurrentStatus());
        Boolean handleResult = handle.statusHandle(context);
        log.info("ContentStatusChangeReceiver#receiveMessage 当前状态处理完成 入参:{}，结果：{}", JSONObject.toJSONString(messageBody), handleResult);

    }
}
